﻿using AutoMapper;
using CK.Sprite.Cache;
using CK.Sprite.Framework;
using JetBrains.Annotations;
using Microsoft.Extensions.Options;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Core
{
    public class DictDbFrameworkCache : DbBaseFrameworkCache<DictVueDto>
    {
        public override string CacheKey => CommonConsts.FrameworkDictCacheKey;

        public override List<DictVueDto> GetBusinessCacheDtos()
        {
            if (!LocalCacheContainer.IsEnabledLocalCache)
            {
                return _serviceProvider.DoDapperService(DefaultDbConfig, (unitOfWork) =>
                {
                    return GetDictVueDtos(unitOfWork);
                });
            }
            else
            {
                return (List<DictVueDto>)LocalCacheContainer.Get($"{CommonConsts.SpriteFormCachePreKey}-{CacheKey}", key =>
                {
                    return _serviceProvider.DoDapperService(DefaultDbConfig, (unitOfWork) =>
                    {
                        return GetDictVueDtos(unitOfWork);
                    });
                });
            }
        }

        private List<DictVueDto> GetDictVueDtos(IUnitOfWork unitOfWork)
        {
            var dictRepository = new GuidRepositoryBase<Dict>(unitOfWork);
            var dictItemRepository = new GuidRepositoryBase<DictItem>(unitOfWork);
            var allDicts = dictRepository.GetAll().ToList();
            var allDictItems = dictItemRepository.GetAll().ToList();

            return allDicts.Select(r =>
            {
                var dictVueDto = new DictVueDto()
                {
                    Id = r.Code,
                    Name = r.Name,
                    DictItemDtos = Mapper.Map<List<DictItemDto>>(allDictItems.Where(t => t.DictCode == r.Code && t.IsActive)).OrderBy(t=>t.Order).ToList()
                };
                return dictVueDto;
            }).ToList();
        }
    }
}
